// formPackage/pages/commissionManager/addNewCommission/addNewCommission.js
import { queryCommissionRules, updateCommissionForHouse, createCommissionForHouse } from "../../../../service/commission_service"
import { settingReportStatus } from "../../../../service/house_service"
import { queryMyCommissionRuleList, companyApplyHouseCommissionJoin, companyCommissionBackFill, updateCompanyHouseCommission, isPushCompanyCommission } from "../../../../service/platform_service"
import { chooseMultipleImgUploadQiniuAction } from "../../../../service/upload_service"
import debounce from "../../../../tools/debounce"
import {
  CHECK_SUCCESS,
  CHECK_FAIL,
  CHECK_PROGRESS
} from "../../../../service/base_service"
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeStyle: "",
    bottomBtnTitle: "创建佣金",
    checkSuccess: CHECK_SUCCESS,
    checkFail: CHECK_FAIL,
    checkProgress: CHECK_PROGRESS,
    showSuccessPop: false,
    successRemindText: "",
    // formData: {
    //   houseNumber: "",
    //   role: "",
    //   roleTypes: [],
    //   roleName: "",
    //   "attachReward": "",//附加奖励
    //   "cashMoney": "",//现金奖
    //   "commission": "",//佣金
    //   "cooperationTime": "",//合作时间
    //   "jumpPoint": "",//跳点
    //   "lookMoney": "",//带看奖励
    //   "ruleId": "",
    //   "name": "",

    // },
    formData: {
      roleTypes: [7, 9],//角色类型
      contractImages: [

      ],//合同图片列表
      commission: {

      }
    },
    commissionData: {
      "attachReward": "",
      "cashMoney": "",
      "commission": "",
      "cooperationTime": "",
      "houseNumber": "",
      "isPush": true,
      "jumpPoint": "",
      "lookMoney": "",
      "ruleId": 0,
      "name": "",
      "proxyCommissionType": "住宅",
    },
    contractImages: [],


    isCloseReport: false,
    singlePopType: "",
    singlePopTitle: "选择",
    showSinglePop: false,
    rulesArr: [],
    customerRuleArr: [],
    isUpdate: false,
    showCSinglePop: false,
    showRuleData: {},
    houseNumber: "",
    roleNameArr: [
      {
        type: 7,
        name: "经纪人",
        isChoose: true,
      },
      {
        type: 9,
        name: "公司",
        isChoose: true,
      }
    ],
    detailId: "",
    examineStatus: 0,//审核状态默认为0
    proxyCommissionTypes: [
      {
        name: "住宅",
        isChoose: true,
      },
      {
        name: "公寓",
        isChoose: false,
      },
      {
        name: "商铺",
        isChoose: false,
      },
      {
        name: "招商",
        isChoose: false,
      },
      {
        name: "写字楼",
        isChoose: false,
      },
    ],

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {


    if (options.houseNumber) {
      this.setData({
        'commissionData.houseNumber': options.houseNumber
      })
    }
    if (options.id) {
      this.setData({
        detailId: options.id
      })
      this.companyCommissionBackFill();
    }




  },
  //回填查询已有佣金详情;
  companyCommissionBackFill() {
    wx.showLoading();
    companyCommissionBackFill(this.data.detailId).then(res => {
      wx.hideLoading();
      console.log("JJLog:回填详情是:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          commissionData: res.data.commission,
          examineStatus: res.data.commission.examineStatus,
          isCloseReport: res.data.commission.isPush,//是否开启报备
          contractImages: res.data.contractImages,
          roleTypes: res.data.roleTypes,
          'formData.roleTypes': res.data.roleTypes,
        })
        this.dealProBack(res.data.commission);
        let type = this.data.roleTypes[0];
        let arr = this.data.roleNameArr;
        arr.forEach((i) => {
          if (i.type == type) {
            i.isChoose = true
          }
        })
        this.setData({
          roleNameArr: arr,
          isUpdate: true,
          bottomBtnTitle: "更新佣金",
        })
        setTimeout(() => {
          this.dealShowRuleData();
        }, 1000);

      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "查询失败",
        icon: "none"
      })
      console.error("JJLog:companyCommissionBackFill", err);
    })
  },
  dealProBack(data) {
    let proCommissionType = data.proxyCommissionType;
    let proArr = proCommissionType.split(",");
    let arr = this.data.proxyCommissionTypes;
    proArr.forEach((i) => {
      arr.forEach((j) => {
        if (i == j.name) {
          j.isChoose = true;
        }
      })
    })
    this.setData({
      proxyCommissionTypes: arr,
    })
  },

  //代理类型选择:
  proxyCommissionAction(e) {
    let index = e.currentTarget.dataset.index;
    let isChoose = e.currentTarget.dataset.item.isChoose;
    let item = 'proxyCommissionTypes[' + index + '].isChoose';
    this.setData({
      [item]: !isChoose,
    })
    let arr = this.data.proxyCommissionTypes;
    let textArr = [];
    arr.forEach((i) => {
      if (i.isChoose) {
        textArr.push(i.name);
      }
    })
    this.setData({
      'commissionData.proxyCommissionType': textArr.join(",")
    })
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.themeStyle) {
      this.setData({
        themeStyle: app.globalData.themeStyle
      })
    }
    this.queryMyCommissionRuleList();
  },
  dealShowRuleData() {
    let ruleId = this.data.commissionData.ruleId;
    let arr = this.data.rulesArr;
    arr.forEach((i) => {
      if (i.id == ruleId) {
        this.setData({
          showRuleData: i,
          'commissionData.name': i.name
        })
      }
    })



  },
  //多行输入回调绑定:
  multiLineBindInput(e) {
    // console.log("JJLog:输入回调:" + JSON.stringify(e));
    let type = e.currentTarget.dataset.type;
    let changeValue = `commissionData.${type}`;
    this.setData({
      [changeValue]: e.detail.value
    })
  },
  //输入绑定
  inputCellChange(e) {
    // console.log("JJLog:e==:" + JSON.stringify(e));
    let detail = e.detail;
    let changeItem = `commissionData.${detail.key}`;
    this.setData({
      [changeItem]: detail.value
    })
  },
  //单线选择点击
  singleSelectPop(e) {
    let type = e.currentTarget.dataset.type;
    if (type == "roleName") {
      //选择角色:
      this.setData({
        singlePopTitle: "选择角色",
        singlePopType: type,
        showSinglePop: true
      })

    }
    if (type == "name") {
      //选择规则：
      if (this.data.customerRuleArr && this.data.customerRuleArr.length < 1) {
        wx.showModal({
          title: '提示',
          content: '您暂未设置佣金规则，是否前往设置？',
          confirmColor: "#FF0000",
          success: res => {
            if (res.confirm) {
              wx.navigateTo({
                url: '/formPackage/pages/platformModule/createNewCommissionRule/createNewCommissionRule',
              })
            }
          }
        })
        return;
      }
      this.setData({
        showCSinglePop: true
      })
    }
  },
  //单项选择回调
  singlePopSelect(e) {
    console.log("JJLog:回调:" + JSON.stringify(e));
    let result = e.detail.result;

    this.setData({
      'formData.role': result.value,
      'formData.roleName': result.label,
      showSinglePop: false
    })

  },
  singleCPopSelect(e) {
    console.log("JJLog:回调来来来:" + JSON.stringify(e));
    let result = e.detail.result;
    this.setData({
      'commissionData.ruleId': result.value,
      'commissionData.name': result.label,
      showCSinglePop: false,
    })

    let arr = this.data.rulesArr;

    arr.forEach((i) => {
      if (i.name == this.data.commissionData.name) {
        this.setData({
          showRuleData: i
        })
      }
    })
  },
  singlePopHide() {
    this.setData({
      showSinglePop: false,
      showCSinglePop: false
    })
  },



  //查询规则:
  queryMyCommissionRuleList() {
    queryMyCommissionRuleList().then(res => {
      console.log("JJLog:规则是:" + JSON.stringify(res));
      if (res.code == 200) {
        if (res.data && res.data.length > 0) {
          this.setData({
            rulesArr: res.data
          })
          this.dealRulesArr(res.data);
        }
      }
    }).catch(err => {
      console.error("JJLog:queryMyCommissionRuleList", err);
    })
  },
  dealRulesArr(arr) {
    let tempArr = [];
    arr.forEach((i) => {
      let obj = {
        label: i.name,
        value: i.id,
      }
      tempArr.push(obj)
    })
    this.setData({
      customerRuleArr: tempArr,
    })
  },
  //提交佣金
  submitAppointmentAction() {
    // console.log("JJLog:数据是:" + JSON.stringify(this.data.formData));

    let data = this.data.commissionData;
    let roleTypes = this.data.formData.roleTypes;
    let images = this.data.contractImages || [];

    if (!data.proxyCommissionType) {
      wx.showToast({
        title: '请至少选择一个代理类型',
        icon: "none"
      })
      return;
    }

    if (roleTypes && roleTypes.length < 1) {
      wx.showToast({
        title: '请选择佣金角色',
        icon: "none"
      })
      return;
    }
    if (!data.commission) {
      wx.showToast({
        title: '请输入佣金金额',
        icon: "none"
      })
      return;
    }
    if (!data.cooperationTime) {
      wx.showToast({
        title: '请输入代理合作有效期',
        icon: "none"
      })
      return;
    }


    if (data.ruleId == "") {
      wx.showToast({
        title: '请选择规则',
        icon: "none"
      })
      return;
    }
    if (images && images.length < 1) {
      wx.showToast({
        title: '请上传代理合同',
        icon: "none"
      })
      return;
    }
    this.setData({
      'formData.commission': this.data.commissionData,
      'formData.contractImages': this.data.contractImages,
    })


    if (this.data.isUpdate) {
      debounce(this.updateCommissionForHouse);
    } else {
      //提交
      debounce(this.companyApplyHouseCommissionJoin);
    }
  },
  //创建一个佣金
  companyApplyHouseCommissionJoin() {
    wx.showLoading();
    console.log("JJLog:上传参数是:" + JSON.stringify(this.data.formData));

    companyApplyHouseCommissionJoin(this.data.formData).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        this.setData({
          successRemindText: "提交成功,管理员审核后生效",
          showSuccessPop: true
        })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "创建失败",
        icon: "none"
      })
      console.error("JJLog:companyApplyHouseCommissionJoin", err);
    })
  },
  updateCommissionForHouse() {
    wx.showLoading();
    console.log(this.data.formData);
    updateCompanyHouseCommission(this.data.formData).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        this.setData({
          successRemindText: "提交成功,管理员审核后生效",
          showSuccessPop: true
        })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "更新失败",
        icon: "none"
      })
      console.error("JJLog:updateCompanyHouseCommission", err);
    })
  },
  //是否关闭或者开启房源报备状态
  upOrDownClick() {
    let status = this.data.isCloseReport;
    let remindText = "";
    if (!status) {
      remindText = "是否开启房源报备?"
    } else {
      remindText = "是否关闭房源报备?"
    }

    wx.showModal({
      title: '提示',
      content: remindText,
      confirmColor: "#FF0000",
      success: res => {
        if (res.confirm) {
          this.settingReportStatus(status);
        }
      }
    })

  },
  settingReportStatus(status) {
    wx.showLoading();
    isPushCompanyCommission(this.data.detailId).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        wx.showToast({
          title: '操作成功',
          icon: "success"
        })
        if (status) {
          this.setData({
            isCloseReport: false
          })
        } else {
          this.setData({
            isCloseReport: true
          })
        }
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "操作失败",
        icon: "none"
      })
    })
  },

  //上传图片控件上传点击:
  pushImgAction(e) {
    console.log("JJLog:上传图片方法点击来了:" + JSON.stringify(e));
    let type = e.detail.type;
    this.pushMultiImgs(type);
  },
  //图片控件删除点击
  deleteImgAction(e) {
    // console.log("JJLog:图片控件删除点击:" + JSON.stringify(e));

    let index = e.detail.deleteIndex;
    let arr = this.data.contractImages;
    arr.splice(index, 1);
    this.setData({
      contractImages: arr
    })

  },
  pushMultiImgs(type) {
    let arr = [];
    let imgType = 2;
    arr = [];
    let tempArr = this.data.contractImages;
    chooseMultipleImgUploadQiniuAction('newImg').then(res => {
      console.log("JJLog:图片上传成功:" + JSON.stringify(res));
      wx.showToast({
        title: '上传成功',
      })


      res.forEach((item) => {
        let obj = {
          "fileType": 1,
          "height": item.height,
          "type": imgType,
          "url": item.complateUrl,
          "width": item.width
        }
        arr.push(obj);
      })
      tempArr = tempArr.concat(arr);
      this.setData({
        contractImages: tempArr
      })
    }).catch(err => {
      console.log("JJLog:图片上传失败:" + JSON.stringify(err));
      wx.showToast({
        title: '图片上传失败',
        icon: "none"
      })
    })
  },

  //角色选择点击:
  roleNameItemAction(e) {
    wx.showToast({
      title: '佣金角色不能更改',
      icon: "none"
    })
    return;

    if (this.data.examineStatus > 0) {
      wx.showToast({
        title: '佣金角色不能更改',
        icon: "none"
      })
      return;
    }
    let item = e.currentTarget.dataset.item;
    let index = e.currentTarget.dataset.index;
    let isChoose = item.isChoose;
    if (isChoose) {
      //已经选中:
      let item = 'roleNameArr[' + index + '].isChoose';
      this.setData({
        [item]: false,
      })
    } else {
      //未选中
      let item = 'roleNameArr[' + index + '].isChoose';
      this.setData({
        [item]: true,
      })
    }
    let arr = [];
    this.data.roleNameArr.forEach((i) => {
      if (i.isChoose) {
        arr.push(i.type)
      }
    })
    this.setData({
      'formData.roleTypes': arr
    })
    console.log("JJLog:选中的角色是:" + JSON.stringify(this.data.formData.roleTypes));
  },

  successPopSure() {
    this.setData({
      showSuccessPop: false,
    })
    wx.navigateBack({
      delta: 0,
    })
  },

})